package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 查询用户地址信息
     * @param address
     * @return
     */
    @Override
    public List<AddressBook> list(AddressBook address) {
        List<AddressBook> addressBookList = addressBookMapper.list(address);
        return addressBookList;
    }

    /**
     * 新增地址信息
     * @param addressBook
     * @return
     */
    @Override
    public void save(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressBookMapper.save(addressBook);
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @Override
    public AddressBook getById(Long id) {
        AddressBook address = addressBookMapper.getById(id);
        return address;
    }

    /**
     * 修改地址信息
     * @param addressBook
     * @return
     */
    @Override
    public void updateAddress(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }

    /**
     * 设置默认地址
     * @param addressBook
     * @return
     */
    @Override
    public void setDefault(AddressBook addressBook) {
        //根据用户id把所有的默认地址取消
        addressBook.setIsDefault(0);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.setDefaultByUserId(addressBook);

        //将当前的地址改为默认地址
        addressBook.setIsDefault(1);
        addressBookMapper.setDefault(addressBook);
    }

    /**
     * 根据id删除地址
     * @param id
     * @return
     */
    @Override
    public void deleteById(Long id) {
        addressBookMapper.deleteById(id);
    }

}
